<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>登录示例</title>
    <!-- 引入 Vue 3 + Axios -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body { font-family: sans-serif; padding: 2rem; }
        .form-group { margin-bottom: 1rem; }
        label { display: block; margin-bottom: 0.5rem; }
        input { padding: 0.5rem; width: 200px; }
        button { padding: 0.5rem 1rem; }
        .message { margin-top: 1rem; }
    </style>
</head>
<body>
<div id="app">
    <h2>用户登录</h2>
    <div class="form-group">
        <label>用户名：</label>
        <input v-model="username" placeholder="请输入用户名" />
    </div>
    <div class="form-group">
        <label>密码：</label>
        <input type="password" v-model="password" placeholder="请输入密码" />
    </div>
    <button @click="login">登录</button>

    <div class="message" v-if="message">
        <strong>{{ message }}</strong>
    </div>
</div>

<script>
    const { createApp } = Vue;

    createApp({
        data() {
            return {
                username: '',  // 绑定到用户名输入框
                password: '',  // 绑定到密码输入框
                message: ''    // 登录结果提示
            };
        },
        methods: {
            async login() {
                this.message = '';
                try {
                    // 1. 向后端服务器发起 POST /login
                    const res = await axios.post('http://139.196.141.180/backend/login', {
                        username: this.username,
                        password: this.password
                    });
                    // 2. 根据业务 code 显示
                    if (res.data.code === 0) {
                        // 存储 token 和 role 到 localStorage
                        localStorage.setItem('token', res.data.token);
                        localStorage.setItem('role', res.data.role);
                        this.message = '🎉 ' + res.data.message+'，正在跳转...';
                        setTimeout(() => {
                            if (res.data.role === 'admin') {
                                window.location.href = 'http://139.196.141.180/admin';
                            } else {
                                window.location.href = 'http://139.196.141.180/normal';
                            }
                        }, 500);
                    } else {
                        this.message = '❌ ' + res.data.message;
                    }
                } catch (err) {
                    // 3. HTTP 错误码处理
                    if (err.response && err.response.data) {
                        this.message = '❌ ' + err.response.data.message;
                    } else {
                        this.message = '❌ 网络或服务器错误';
                    }
                }
            }
        }
    }).mount('#app');
</script>
</body>
</html>
